<template>
  <div class="reportPreview">
    <div ref="reportPreviewBox" class="reportPreviewBox">
      <div v-show="!isPdf">
        <p v-show="isConfirm === 'true' && isShowConfirmText">{{ $t('caseorder.anli92') }}</p>
        <p v-show="isConfirm === 'false' && isShowConfirmText">{{ $t('caseorder.anli93') }}</p>
      </div>
      <h3 class="reportPreview_title">{{ $t('caseorder.anli82') }}</h3>
      <div class="reportPreview_sub_title">
        <span>{{ $t('caseorder.anli83') }}：{{ reportData.generationTime }}</span>
        <span>{{ $t('caseorder.anli84') }}：{{ reportData.reviewedBy }}</span>
      </div>

      <div class="reportPreview_info">
        <div>
          <span class="result_text">{{ $t('caseorder.anli85') }}</span>
          <span class="result_reason" v-show="reportResult">{{ $t('caseorder.anli86') }}</span>
          <span class="result_reason" v-show="!reportResult">{{ $t('caseorder.anli87') }}</span>
        </div>
        <div class="reportPreview_info_box">
          <el-row>
            <el-col :span="is3column ? 8 : 12">
              <span
                >{{ $t('caseorder.anli64') }}：{{
                  dataObj && dataObj.order ? dataObj.order.id : '--'
                }}</span
              >
            </el-col>
            <el-col :span="is3column ? 8 : 12">
              <span
                >{{ $t('caseorder.yulan.yulan38') }}：
                {{ dataObj && dataObj.order ? dataObj.order.patientName : '--' }}</span
              >
            </el-col>
            <el-col :span="is3column ? 8 : 12">
              <span
                >{{ $t('caseorder.yulan.yulan117') }}：{{
                  dataObj && dataObj.order ? dataObj.order.orderDataTypeName : '--'
                }}</span
              >
            </el-col>

            <el-col :span="is3column ? 8 : 12">
              <span
                >{{ $t('caseorder.yulan.yulan3') }}：{{
                  dataObj && dataObj.order ? dataObj.order.doctorName : '--'
                }}</span
              >
            </el-col>
            <el-col :span="is3column ? 8 : 12">
              <span
                >{{ $t('caseorder.yulan.yulan4') }}：{{
                  dataObj && dataObj.order ? dataObj.order.creatorDeptName : '--'
                }}</span
              >
            </el-col>
            <el-col :span="is3column ? 8 : 12">
              <span
                >{{ $t('caseorder.yulan.yulan108') }}：{{
                  dataObj && dataObj.order ? dataObj.order.skillDeptName : '--'
                }}</span
              >
            </el-col>
          </el-row>
        </div>
      </div>

      <div class="screenshot">
        <Screenshot :mouthImgs="reportData.mouthImgs" />
      </div>

      <div class="review_list">
        <div class="detail_header">
          <span class="title">{{ $t('caseorder.anli75') }}</span>
        </div>
        <reviewList
          ref="reviewList"
          :isshowQualified="true"
          :isReport="true"
          :isPreview="isPreview"
          :res_form="res_form"
        />
      </div>
    </div>

    <!-- 二维码占位 -->
    <div id="qrCode_seat" ref="qrCode_seat" style="display: none"></div>
  </div>
</template>

<script>
import Screenshot from '@/views/order/common/Screenshot';
import reviewList from '@/views/order/common/reviewList';
import { formatDate } from '@/utils/index';
import Cookies from 'js-cookie';
import { downloadPDF } from '@/utils/pdf.js';

import QRCode from 'qrcodejs2';
export default {
  name: 'reportPreview',

  components: {
    Screenshot,
    reviewList,
  },
  props: {
    // 确定是确认接单还是拒绝接单
    isConfirm: {
      type: String,
    },
    // 传过来组织的数据
    res_form: {
      type: Object,
    },
    // 判断订单信息是3列还是两列
    is3column: {
      type: Boolean,
    },
    // 判断是否出现是否确认接单相关字样
    isShowConfirmText: {
      type: Boolean,
    },
  },
  data() {
    return {
      reportData: {
        generationTime: '',
        reviewedBy: '',
        mouthImgs: [],
      },
      dataObj: {},
      QRCode: null,
      codeUrl: '',
      reportResult: false,
      isPreview: false,
      // 控制是否是pdf导出
      isPdf: false,
    };
  },
  watch: {
    res_form: {
      handler(newVal) {
        this.res_form = newVal;

        this.getTitleData();
      },
      deep: true, // 开启深度监听
    },
  },

  created() {
    // 获取审核报告生成时间和审核人
    this.getTitleData();

    // 获取订单信息数据
    this.getOrderInfo();
  },
  mounted() {},

  methods: {
    getTitleData() {
      if (this.res_form.reportTime) {
        this.reportData.generationTime = this.res_form.reportTime;
      } else {
        this.reportData.generationTime = formatDate(new Date(), 'second');
      }

      this.reportData.reviewedBy = window.localStorage.getItem('user_realName');
    },
    getOrderInfo() {
      var languageType = localStorage.getItem('lang');
      if (languageType === undefined || languageType === null) {
        languageType = 'cn';
      }
      this.$http
        .get(
          `/order/selectDetail?id=${
            this.$route.query.id
          }&languageType=${languageType.toString()}&token=${Cookies.get('token')}&timeZone=${
            this.$timeZone
          }`,
        )
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.dataObj = res.data;

            // if (this.dataObj.order.orderStatus === 4) {
            //   // 拒绝接单
            //   this.reportResult = false;
            // } else if (this.dataObj.order.orderStatus === 2) {
            //   // 审核通过
            //   this.reportResult = true;
            // } else {
            //   if (this.isConfirm) {
            //     this.reportResult = true;
            //   } else {
            //     this.reportResult = false;
            //   }
            // }
            console.log('isConfirm---', typeof this.isConfirm);
            if (this.isConfirm) {
              if (this.isConfirm === 'true') {
                this.reportResult = true;
              } else if (this.isConfirm === 'false') {
                this.reportResult = false;
              }
            } else {
              if (this.dataObj.order.orderStatus === 4) {
                this.reportResult = false;
              } else {
                this.reportResult = true;
              }
            }
            if (res.data.order.mouthImgs) {
              let count = 0;
              const newMouthImgs = JSON.parse(res.data.order.mouthImgs);
              newMouthImgs.forEach((item) => {
                count++;
                if (item.url) {
                  var image = new Image();
                  image.src = item.url + '?v=' + Math.random(); // 处理缓存
                  image.crossOrigin = '*'; // 支持跨域图片
                  image.onload = () => {
                    var canvas = document.createElement('canvas');
                    var context = canvas.getContext('2d');
                    canvas.width = image.width;
                    canvas.height = image.height;
                    context.drawImage(image, 0, 0, image.width, image.height);
                    const ndata = canvas.toDataURL('image/jpeg', 1.0);
                    item.url = ndata;
                  };
                }
              });
              if (count == newMouthImgs.length) {
                this.reportData.mouthImgs = newMouthImgs;
              }
            }
          }
        })
        .catch((err) => {
          console.log('err', err);
        });
    },

    reportConfirm(callback) {
      // 确认接单
      this.$nextTick(() => {
        this.$refs.reviewList.isPreview = true;
        this.generateCode();
        this.$http
          .post('/order/orderAffirm', {
            id: this.$route.query.id,
            orderDesignAutoCheck: this.dataObj.order.orderDesignAutoCheck,
            orderReviewReportCheck: 1,
          })
          .then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg);
            } else {
              this.isPdf = true;
              this.$nextTick(() => {
                // 生成pdf并发送消息
                downloadPDF(this.$refs.reportPreviewBox, this.dataObj, false, (pdfData) => {
                  setTimeout(() => {
                    this.sendMsg(pdfData, callback);
                  }, 500);
                });
              });
            }
          })
          .catch((err) => {
            console.log('err', err);
          });
      });
    },

    /***
     * res是pdf的base64
     * res1是二维码的base64
     *
     */
    sendMsg(pdfBase64Str, callback) {
      let title = `${this.dataObj.order.patientName ? this.dataObj.order.patientName : '-'}_${
        this.reportData.generationTime
      }_${this.$t('caseorder.anli82')}.pdf`;
      // pdf文件
      let pdf_file = this.dataURLtoFile(pdfBase64Str, title); //调用一下下面的转文件流函数
      /***
       * 生成二维码文件
       *
       */
      let qrCode_seat_ref = document.getElementById('qrCode_seat');
      let qrCode_seat_ref_img = qrCode_seat_ref.querySelectorAll('img')[0];
      let code_base64 = qrCode_seat_ref_img.getAttribute('src');
      let code_title = `${this.dataObj.order.patientName ? this.dataObj.order.patientName : '-'}_${
        this.reportData.generationTime
      }_${this.$t('caseorder.anli82')}.png`;
      let code_file = this.dataURLtoFile(code_base64, code_title);
      // 传递参数
      let formData = new FormData();
      formData.append('file', pdf_file); // 文件对象
      formData.append('file', code_file); // 文件对象
      this.$http({
        url: '/tools/uploadMulti',
        method: 'post',
        data: formData,
      })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            let fileList = res.data;
            fileList.forEach((item) => {
              item.url = item.filepath;
              item.fileName = item.oldName;
            });
            let param = {
              fileList: fileList,
              orderId: this.$route.query.id,
            };
            this.$http
              .post('/orderMessage/addMessage', param)
              .then(({ data: res }) => {
                if (res.code !== 0) {
                  return this.$message.error(res.msg);
                } else {
                  this.$message.success(this.$t('caseorder.yulan.yulan100'));
                  callback && callback();
                }
              })
              .catch((err) => {
                console.log('err', err);
                this.loading = false;
              });
          }
        })
        .catch((err) => {
          console.log('err', err);
        });
    },
    dataURLtoFile(dataurl, filename) {
      let arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
    // 生成二维码(这里是为了发送二维码消息)
    generateCode() {
      // 先生成二维码
      var languageType = localStorage.getItem('lang');
      if (languageType === undefined || languageType === null) {
        languageType = 'cn';
      }
      let user_realName = window.localStorage.getItem('user_realName');
      this.codeUrl = `${this.$config.ip}/#/reportPreview_phone?user_realName=${user_realName}&id=${
        this.$route.query.id
      }&languageType=${languageType.toString()}&token=${Cookies.get('token')}&timeZone=${
        this.$timeZone
      }`;
      this.QRCode = new QRCode(this.$refs.qrCode_seat, {
        text: this.codeUrl,
        width: 200,
        height: 200,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.L, // 容错率，L/M/H
      });
    },
    // 拒绝接单
    refuseOrder(callback) {
      this.$nextTick(() => {
        this.$refs.reviewList.isPreview = true;
        this.generateCode();
        this.$http
          .post('/order/orderReject', { id: this.$route.query.id, orderReviewReportCheck: 1 })
          .then(({ data: res }) => {
            this.isPdf = true;
            if (res.code !== 0) {
              return this.$message.error(res.msg);
            } else {
              this.$nextTick(() => {
                this.$message.success(this.$t('add.add26'));
                downloadPDF(this.$refs.reportPreviewBox, this.dataObj, false, (pdfData) => {
                  setTimeout(() => {
                    this.sendMsg(pdfData, callback);
                  }, 500);
                });
              });
            }
          })
          .catch((err) => {
            console.log('err', err);
          });
      });
    },

    toExportPdf() {
      this.isPreview = true;
      this.$nextTick(() => {
        downloadPDF(this.$refs.reportPreviewBox, this.dataObj, true, () => {
          this.isPreview = false;
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.reportPreview {
  height: calc(100% - 50px);
  font-size: 16px;
  // height: 650px;
  overflow: auto;
  margin-top: 10px;

  > .reportPreviewBox {
    overflow: auto;

    p {
      color: red;
      margin-bottom: 15px;
    }
  }

  > div {
    margin-top: 10px;
    width: 99%;
    padding: 15px;
  }

  .detail_header {
    margin-bottom: 10px;

    .title {
      font-size: 16px;
      font-weight: 800;
      line-height: 20px;
      color: #003e67;
    }
  }

  .reportPreview_title {
    text-align: center;
    margin-bottom: 15px;
  }

  .reportPreview_sub_title {
    text-align: center;

    span {
      display: inline-block;
      margin-right: 15px;
    }
  }

  .reportPreview_info {
    margin-top: 15px;

    > div:nth-child(1) {
      display: flex;
      align-items: center;
    }

    .result_text {
      padding: 10px;
      background: #003e67;
      color: #ffffff;
      display: inline-block;
      margin-right: 10px;
      width: 150px;
      text-align: center;
    }

    .result_reason {
    }

    .reportPreview_info_box {
      margin-top: 15px;
      padding: 10px;
      border: 1px solid #ebeef5;

      span {
        display: inline-block;
        height: 35px;
        line-height: 35px;
      }
    }
  }
}
</style>
